package com.jiaying.sync;

import com.mongodb.ReadPreference;
import com.mongodb.client.*;
import com.mongodb.client.result.InsertOneResult;
import com.mongodb.connection.ClusterDescription;
import com.mongodb.connection.ServerDescription;
import org.bson.Document;

import com.jiaying.sync.config.MongoConfig;

import java.util.List;

/**
 * 专门测试从库信息打印功能的类
 */
public class SecondaryServerTest {
    private MongoClient mongoClient;
    private MongoConfig config;
    
    public static void main(String[] args) {
        SecondaryServerTest test = new SecondaryServerTest();
        try {
            test.initializeConnection();
            test.testSecondaryServerInfo();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            test.closeConnection();
        }
    }
    
    /**
     * 初始化MongoDB连接
     */
    public void initializeConnection() {
        try {
            // 初始化配置
            config = new MongoConfig();
            
            // 构建连接字符串
            String connectionString = "mongodb://" + config.getClusterHosts();
            
            // 创建MongoClient实例
            mongoClient = MongoClients.create(connectionString);
            
            System.out.println("成功连接到MongoDB集群: " + config.getClusterHosts());
        } catch (Exception e) {
            System.err.println("连接MongoDB集群失败: " + e.getMessage());
            throw e;
        }
    }
    
    /**
     * 测试从库信息打印功能
     */
    public void testSecondaryServerInfo() {
        try {
            System.out.println("=== 测试从库信息打印功能 ===");
            
            MongoDatabase database = mongoClient.getDatabase(config.getDatabaseName());
            MongoCollection<Document> collection = database.getCollection(config.getCollectionName());
            
            // 使用secondaryPreferred读偏好进行读操作
            MongoCollection<Document> readCollection = collection.withReadPreference(ReadPreference.secondaryPreferred());
            
            // 执行读操作
            Document readDoc = readCollection.find().first();
            if (readDoc != null) {
                // 打印从库信息
                printSecondaryServerInfo();
                System.out.println("从节点读取数据: " + readDoc.toJson());
            } else {
                System.out.println("未找到数据");
            }
            
            System.out.println("从库信息测试完成");
        } catch (Exception e) {
            System.err.println("从库信息测试失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 打印从库服务器信息
     */
    private void printSecondaryServerInfo() {
        try {
            ClusterDescription clusterDescription = mongoClient.getClusterDescription();
            List<ServerDescription> serverDescriptions = clusterDescription.getServerDescriptions();
            
            System.out.println("当前集群中的服务器:");
            for (ServerDescription serverDesc : serverDescriptions) {
                System.out.println("  服务器地址: " + serverDesc.getAddress() + 
                                  ", 类型: " + serverDesc.getType() + 
                                  ", 状态: " + serverDesc.getState() +
                                  (serverDesc.isPrimary() ? " (主节点)" : " (从节点)"));
            }
            
            // 查找从节点
            ServerDescription secondaryServer = null;
            for (ServerDescription serverDesc : serverDescriptions) {
                if (serverDesc.getType().toString().contains("SECONDARY") && 
                    serverDesc.getState().toString().equals("CONNECTED")) {
                    secondaryServer = serverDesc;
                    break;
                }
            }
            
            if (secondaryServer != null) {
                System.out.println("当前读操作使用的从库: " + secondaryServer.getAddress());
            } else {
                System.out.println("当前未找到可用的从库");
            }
        } catch (Exception e) {
            System.err.println("获取服务器信息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 关闭连接
     */
    public void closeConnection() {
        if (mongoClient != null) {
            mongoClient.close();
            System.out.println("MongoDB连接已关闭");
        }
    }
}